<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>hash路由</title>
</head>

<body>


  <div id="app">
    <h1>hash路由</h1>
    <button data-url="/center">个人主页</button>
    <button data-url="/music">音乐</button>
    <button data-url="/news">新闻</button>
    <div id="view"></div>
  </div>

</body>

<script>
  //定义路由表
  const routes = [
    { path: "/center", msg: "制作主页好难偶" },
    { path: "/music", msg: "紅蓮華" },
    { path: "/news", msg: "股市暴跌" }
  ]


  /* 
  
  */

  //遍历所有按钮绑定事件
  const oBtns = document.querySelectorAll("#app button")
  const oView = document.getElementById("view");


  for (var i = 0; i < oBtns.length; i++) {
    oBtns[i].onclick = function () {
      //获取当前路由跳转的按钮上保存的path信息 然后改变地址栏地址的hash值
      // console.log(this.dataset.url);
      location.hash = this.dataset.url;
    };
  }

  //我们要通过onhashchange事件 监听当前的url的hash值的变化
  window.onhashchange = function (e) {
    console.log(e);
    //在event事件对象上拿到当前监听的新的hash地址
    const newURL = e.newURL.split("#")[1];

    // console.log("hash地址发生改变了");
    //拿到当前的hash和路由表中的path进行一一对比,更新对应的视图
    routes.forEach((route) => {
      if (route.path === newURL) {
        //更新视图
        oView.textContent = route.msg;
      }
    });
  };




</script>

</html>